package com.example.multinetty.netty.send;

import com.example.multinetty.netty.firstprotocal.SelfResponse;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;
import lombok.Data;
import org.springframework.util.StringUtils;
@Data

public class ChannelSender {
    private Channel channel;

    public ChannelSender(Channel channel) {
        this.channel = channel;
    }

    public void sendback(String message) {


        String result = message;//servletResponse.getContentAsString();
        //String result = servletResponse.getForwardedUrl();

        result = StringUtils.isEmpty(result) ? "" : result;

        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(200), Unpooled.copiedBuffer(result, CharsetUtil.UTF_8));
        SelfResponse selfResponse = new SelfResponse(response);
        response.headers().set("Content-Type", "text/json;charset=UTF-8");
        response.headers().set("Access-Control-Allow-Origin", "*");
        response.headers().set("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,X-File-Name");
        response.headers().set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        response.headers().set("Content-Length", Integer.valueOf(response.content().readableBytes()));
        response.headers().set("Connection", "keep-alive");
        //ChannelFuture writeFuture = channelHandlerContext.writeAndFlush(response);
        ChannelFuture writeFuture = channel.writeAndFlush(selfResponse);
        //writeFuture.addListener(ChannelFutureListener.CLOSE);
    }
}
